package custom_http

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func HttpGet[T any](url string) (T, error) {
	var zero T // 零值，用于错误时返回

	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	resp, err := client.Get(url)
	if err != nil {
		return zero, fmt.Errorf("发起请求失败: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return zero, fmt.Errorf("HTTP 请求失败，状态码: %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return zero, fmt.Errorf("读取响应体失败: %w", err)
	}

	var result T
	if err := json.Unmarshal(body, &result); err != nil {
		return zero, fmt.Errorf("JSON 解析失败: %w", err)
	}

	return result, nil
}
